//
//  RegViewController.m
//  ScalperMerchant
//
//  Created by 王云 on 2017/10/6.
//  Copyright © 2017年 WY. All rights reserved.
//

#import "RegViewController.h"
#import "BusinessAgreeController.h"
#import "WXApi.h"
#import "IdentitySViewController.h"
#import "SCLoginBindingController.h"
#import "HomeController.h"

@interface RegViewController ()<UITextFieldDelegate>

@end

@implementation RegViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"注册";
    if (![WXApi isWXAppInstalled]) {
        _WXBtn.hidden = YES;
        _orImg.hidden = YES;
    }
    _WXBtn.tag = UMSocialPlatformType_WechatSession;
    _PromptL.attributedText = [WYNSString Att:@"温馨提示:\n微信公众号用户可直接点以下微信图标，来同步账号数据。请不要重新注册账号，否则原公众号数据将不能同步。" rang:@"温馨提示:" font:[UIFont systemFontOfSize:15] color:KOrange ParagraphSpacing:8];
}
- (IBAction)regClick:(id)sender {
    
    [self.view endEditing:YES];
    
    if (![HWCommon isMobileNumber:_phoneF.text]) {
        [SCTool showError:@"请输入正确手机号码"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_phoneF becomeFirstResponder];
        });
        return;
    }
    if (_pwdF.text.length < 6) {
        [SCTool showError:@"密码输入过短"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_pwdF becomeFirstResponder];
        });
        return;
    }
   
    if (_verF.text.length == 0) {
        [SCTool showError:@"验证码错误"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_verF becomeFirstResponder];
        });
        return;
    }


    __weak __typeof(&*self)weakSelf = self;
    [SCApiTool ScRegMember_mobile:_phoneF.text member_passwd:_pwdF.text
                             code:_verF.text  success:^(NSDictionary *dic) {
        [SCTool showMessage:@"注册成功"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });

    } failure:^(NSString *errormsg) {
        
        [SCTool showError:errormsg];
        
        [weakSelf.verButton setBackgroundColor:KOrange];
        [weakSelf.verButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        weakSelf.verButton.userInteractionEnabled = YES;

    }];

}

- (IBAction)verClick:(id)sender {
    
    [self.view endEditing:YES];
    __weak __typeof(&*self)weakSelf = self;
    if (![HWCommon isMobileNumber:_phoneF.text]) {
        [SCTool showError:@"请输入正确手机号"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.phoneF becomeFirstResponder];
        });
        return;
    }
    [SCApiTool ScCheckexist:_phoneF.text success:^(NSString *msg) {
        [self verCode];
        
    } failure:^(NSString *errormsg) {
        [SCTool showMessage:errormsg];
    }];
}
- (void)verCode{
    
    
    __block NSInteger timeout=59;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    [SCApiTool ScSendPhone:_phoneF.text type:@"register" success:^(NSString *verStr) {
        [SCTool showSuccess:verStr];
        
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_verButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                    _verButton.userInteractionEnabled = YES;
                    _verButton.backgroundColor = KOrange;
                });
            }else{
                NSInteger seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2ld", (long)seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_verButton setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                    _verButton.userInteractionEnabled = NO;
                    [_verButton setBackgroundColor:WYColor(215, 215, 215)];
                });
                timeout--;
                
            }
        });
        dispatch_resume(_timer);
        
    } failure:^(NSString *msg) {
        [SCTool showError:msg];
        [_verButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _verButton.userInteractionEnabled = YES;
        _verButton.backgroundColor = KOrange;
    }];
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_verButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    _verButton.userInteractionEnabled = YES;
    _verButton.backgroundColor = KOrange;
}

#pragma mark - textFiled delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == _pwdF){
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 20) {
            return NO;
        }
    }
    else if (textField == _phoneF){
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
        
    }
        else if (textField == _verF){
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 10) {
            return NO;
        }
        
    }
    return YES;
}
- (IBAction)WXClick:(UIButton *)sender {
    
    UMSocialPlatformType snsNameType ;
    switch (sender.tag) {
        case UMSocialPlatformType_WechatSession:
            snsNameType = UMSocialPlatformType_WechatSession;
            break;
        default: snsNameType = UMSocialPlatformType_WechatSession;
            break;
    }
    __weak __typeof(&*self)weakSelf = self;
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:snsNameType currentViewController:self completion:^(id result, NSError *error) {
        
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 第三方登录数据(为空表示平台未提供)
            // 授权数据
            NSLog(@" uid: %@", resp.uid);
            NSLog(@" openid: %@", resp.openid);
            NSLog(@" accessToken: %@", resp.accessToken);
            NSLog(@" refreshToken: %@", resp.refreshToken);
            NSLog(@" expiration: %@", resp.expiration);
            
            // 用户数据
            NSLog(@" name: %@", resp.name);
            NSLog(@" iconurl: %@", resp.iconurl);
            NSLog(@" gender: %@", resp.unionGender);
            
            // 第三方平台SDK原始数据
            NSLog(@" originalResponse: %@", resp.originalResponse);
            [weakSelf snsName:snsNameType snsAccount:resp];
        }
        
    }];
}
- (void)snsName:(UMSocialPlatformType )snsNameType snsAccount:(UMSocialUserInfoResponse *)snsAccount {
    
    if (snsNameType == UMSocialPlatformType_WechatSession){
        
        __weak __typeof(&*self)weakSelf = self;
        [SCTool showLoading:@"登录中"];
        [SCApiTool ScLoginMember_mobile:@"" member_passwd:@"" unionid:snsAccount.unionId headimgurl:snsAccount.iconurl nickname:snsAccount.name sex:snsAccount.unionGender success:^(NSString *msg) {
            
            [SCTool showSuccess:@"登录成功"];
            SCUser *user = [SCUserTool loadInfo];
            if (user.member_mobile_bind == 1) {
                
                if ([[SCUserTool loadInfo].joinin_state isEqualToString:@"0"]) {
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        IdentitySViewController *identityVC = [[IdentitySViewController alloc] init];
                        [weakSelf.navigationController pushViewController:identityVC animated:YES];
                        
                    });
                    
                }else{
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [UIApplication sharedApplication].keyWindow.rootViewController =[[JTNavigationController alloc] initWithRootViewController:[[HomeController alloc] init]]; ;
                    });
                }
                
                
            }else{
                SCLoginBindingController *logBinVC = [[SCLoginBindingController alloc] init];
                logBinVC.unioid = snsAccount.unionId;
                [self.navigationController pushViewController:logBinVC animated:YES];
            }
            
            
        } failure:^(NSString *errormsg) {
            [SCTool showError:errormsg];
        }];
        
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}



@end
